<template>
    <div class="update-photo">
        <img  class="img" :src="img" ref="img">
        <div class="bottom-wrap">
            <div class="cancel" @click="$emit('close')">取消</div>
            <div class="confirm" @click="onConfirm">确认</div>
        </div>
    </div>
  </template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  components: {},
  props: {
    img: {
      type: String,
      required: true

    }
  },
  data () {
    return {
      cropper: null
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {
    const img = this.$refs.img
    this.cropper = new Cropper(img, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  },
  methods: {
    onConfirm () {
      this.cropper.getCroppedCanvas().toBlob(blob => {
        this.updatePhoto(blob)
      })
    },
    async updatePhoto (blob) {
      try {
        this.$toast.loading({
          duration: 0, // 持续时间，0表示持续展示不停止
          forbidClick: true, // 是否禁止背景点击
          message: '图像修改中...' // 提示消息
        })

        const formData = new FormData()
        formData.append('photo', blob)
        const { data } = await updateUserPhoto(formData)
        this.$emit('update-photo', data.data.photo)
        this.$emit('close')
        this.$toast.success('图像更新成功')
      } catch (err) {
        window.console.log(err)
        this.$toast.fail('图像更新失败')
      }
    }
  }
}
</script>

  <style scoped lang="less">
.update-photo{
    width: 100%;
    height: 100%;

    background-color: #000;

    .img{
        max-width: 100%;
        display: block;
    }
    .bottom-wrap{
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        display: flex;
        justify-content: space-between;
        .confirm, .cancel{
            width: 90px;
            height: 90px;
            font-size: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
        }
    }
}
  </style>
